package cn.caplike.demo.nio._2017;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

/**
 * 简介：Buffer
 *
 * @author 李珂 2017年11月22日 上午11:20:47
 */
public class BufferTest {

    public static void run() {
        ByteBuffer buf0 = ByteBuffer.allocate(48);
        buf0.put(new byte[]{1, 2, 4});
        buf0.flip(); // 从写到读的转换
        while (buf0.hasRemaining()) {
            System.out.println(buf0.get());
        }

        System.out.println("---------------------------------------------------------------------------------------------------------");

        String text = "李珂";
        ByteBuffer buf1 = ByteBuffer.allocate(96);
        buf1.asCharBuffer().put(text);
        // buf1.flip();
        // System.out.println(buf1.limit()); // 0
        buf1.limit(text.length() * Character.BYTES);
        while (buf1.hasRemaining()) {
            System.out.println(buf1.getChar());
        }

        System.out.println("---------------------------------------------------------------------------------------------------------");

        ByteBuffer buf2 = ByteBuffer.allocate(1024);
        IntBuffer ib = buf2.asIntBuffer();
        ib.put(new int[]{1, 42, 12, -12});
        /*
         * 将ByteBuffer转化为IntBuffer视图后，再调用put，ByteBuffer中的position指针不会移动
         * 但是所生成的IntBuffer中的position会按正常方式移动 而且整个IntBuffer的capacity会按照byte 和 int
         * 之间的所占字节大小比例而改变
         */
        System.out.println("ByteBuffer.position = " + buf2.position());
        System.out.println("ByteBuffer.limit = " + buf2.limit());
        System.out.println("ByteBuffer.capacity = " + buf2.capacity());
        System.out.println("IntBuffer.position = " + ib.position());
        System.out.println("IntBuffer.limit = " + ib.limit());
        System.out.println("IntBuffer.capacity = " + ib.capacity());
        ib.flip();
        while (ib.hasRemaining()) {
            System.out.println(ib.get());
        }

    }

}
